//
//  SceneDelegate.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/7/27.
//

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    var currentBrightness: CGFloat = 0

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        currentBrightness = UIScreen.main.brightness
        guard let _ = (scene as? UIWindowScene) else { return }
        
        openUrl(url: connectionOptions.urlContexts.first?.url)
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        print("sceneDidDisconnect")
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        let vc = UIViewController.currentViewController()
        if !(vc is TimingViewController || vc is TimingSettingsController) {
            return
        }
        
        let flag = UserDefaults.standard.bool(forKey: kUserDefaults_BrightnessSwitch)
        if flag {
            let value = UserDefaults.standard.float(forKey: kUserDefaults_BrightnessValue)
            UIScreen.main.brightness = CGFloat(value)
        }
    }

    func sceneWillResignActive(_ scene: UIScene) {
        let vc = UIViewController.currentViewController()
        if !(vc is TimingViewController || vc is TimingSettingsController) {
            return
        }
        
        let flag = UserDefaults.standard.bool(forKey: kUserDefaults_BrightnessSwitch)
        if flag {
            UIScreen.main.brightness = currentBrightness
        }
    }

    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        openUrl(url: URLContexts.first?.url)
    }
    
    func sceneWillEnterForeground(_ scene: UIScene) {
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
    }
    
    private func openUrl(url: URL?) {
        guard let url = url else {
            print("url空")
            return
        }
        
        print("url:\(url)")
        
        if url.scheme == "file" {
            let vc = ImportFileDataController()
            vc.fileUrl = url
            UIViewController.currentNavController()?.pushViewController(vc, animated: true)
            return
        }
        
        var type = TimeStatisticsType.xingce
        if url.absoluteString.contains("timing/xingce") {
            type = .xingce
        } else if url.absoluteString.contains("timing/ziliaofenxi") {
            type = .ziliaofenxi
        } else if url.absoluteString.contains("timing/shenlun/lianti") {
            type = .shenlunlianti
        } else if url.absoluteString.contains("timing/shenlun/mokao") {
            type = .shenlun
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.8, execute: {
            let vc = TimingViewController()
            vc.type = type
            UIViewController.currentNavController()?.pushViewController(vc, animated: true)
        })
    }
}

